package com.personal.website.lottery.web.controller.admin;

import com.personal.website.lottery.web.model.User;
import com.personal.website.lottery.web.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;

/**
 * Created by 10171225 on 2016/6/23.
 */
@Controller
@RequestMapping("/admin/memberManage")
public class MemberManageController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Resource
    private UserService userService;

    @RequestMapping("/memberDelete")
    @ResponseBody
    public String memberDelete(HttpServletRequest request) {
        int memberId = -1;
        try {
            memberId = Integer.parseInt(request.getParameter("noticeId"));
            User member = this.userService.getUserById(memberId);
            if (member == null) {
                logger.error(String.format("删除会员'%d'时，会员不存在！", memberId));
                return "不存在该会员！";
            }
            if (this.userService.deleteUser(memberId)) {
                logger.info(String.format("删除会员'%d'，删除成功！", memberId));
                return "删除成功！";
            } else {
                logger.error(String.format("删除会员'%d'，删除失败！", memberId));
                return "删除失败！";
            }
        } catch (Exception e) {
            logger.error(String.format("未知异常，删除失败！", memberId), e);
            return "删除失败！";
        }
    }

    @RequestMapping("/memberSearch")
    public String memberSearch(HttpServletRequest request, Model model) {
        String text = null;
        try {
            text = request.getParameter("text");
            text = URLDecoder.decode(text, "UTF-8");
            model.addAttribute("searchInput", text);
            model.addAttribute("memberList",this.userService.getUserLikeUserName("%" + text + "%", 50));
        } catch (Exception e) {
            logger.error(String.format("搜索会员名为'%s'的会员时失败！", text), e);
        }
        return "admin/memberManage";
    }
}
